package com.sunseagear.wind.modules.sso.controller;

import com.sunseagear.common.base.http.R;
import com.sunseagear.common.base.satoken.entity.LoginUser;
import com.sunseagear.common.base.satoken.utils.UserUtils;
import com.sunseagear.common.utils.StringUtils;
import com.sunseagear.wind.common.aspectj.annotation.RepeatSubmit;
import com.sunseagear.wind.modules.sso.entity.bo.LoginBo;
import com.sunseagear.wind.modules.sso.service.IOAuthService;
import com.sunseagear.wind.common.utils.LoginLogUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @version V1.0
 * @package com.sunseagear.api.web.controller
 * @title:
 * @description: Oauth2.0认证开发 * @date: 2018/1/8 15:56
 * @copyright: 2017 www.sunseagear.com Inc. All rights reserved.
 */
@RestController
@RequestMapping("/sso/oauth2")
@RequiredArgsConstructor
public class Oauth2Controller {

    private final IOAuthService oAuthService;


    /**
     * 登陆方法
     */
    @RepeatSubmit(expireSeconds = 2)
    @PostMapping("/accessToken")
    public R<LoginUser> accessToken(@RequestBody LoginBo loginBo) {
        String username = loginBo.getUsername();
        String password = loginBo.getPassword();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return R.fail("用户名密码不能为空");
        }
        LoginUser loginUser = oAuthService.passwordAuthLogin(loginBo);
        LoginLogUtils.recordSuccessLoginLog(username, "登录成功");

        return R.success(loginUser);
    }


    /**
     * 回收TOKEN
     */
    @RequestMapping("/revokeToken")
    public R<Void> revokeToken(HttpServletRequest request) {
        String accessToken = request.getHeader("Authorization");
        String username = UserUtils.getUsername();
        oAuthService.revokeToken(accessToken);
        LoginLogUtils.recordLogoutLoginLog(username, "退出成功");
        return R.success("退出成功");
    }
}

